package io.potato.core.config;

import io.potato.core.cache.Cache;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.Serializable;

/**
 * 可缓存的Domain配置工厂
 *
 * @author longshangbo@163.com
 *
 * <p>2017年8月1日 上午11:09:08</p>
 */
public abstract class CacheableDomainConfigFactory<T extends Serializable> implements DomainConfigFactory<T> {
	
	/**
	 * 日志对象
	 */
	protected static final Log LOGGER = LogFactory.getLog(CacheableDomainConfigFactory.class);

	@Override
	public T create(Class<?> domainClass) {
		Cache<Class<?>, T> cache = getCache();
		T config = cache.get(domainClass);
		
		if(config == null){
			synchronized (domainClass) {
				if(config == null){
					config = buildConfig(domainClass);
					cache.put(domainClass, config);
					
					if(LOGGER.isInfoEnabled()){
						LOGGER.info("Build configuration [" + domainClass + "] success.");
					}
				}
			}
		}
		
		return config;
	}
	
	@Override
	public void destroy() throws Exception {
		getCache().clear();
	}
	
	/**
	 * 获取缓存对象
	 * 
	 * @return 缓存对象
	 */
	protected abstract Cache<Class<?>, T> getCache();
	
	/**
	 * 构造配置
	 * 
	 * @param domainClass domain Class
	 * @return 配置对象
	 */
	protected abstract T buildConfig(Class<?> domainClass);
	
}
